package com.dtjd.playcoinmonkey.activities;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MenuItem;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import com.dtjd.playcoinmonkey.MyApplication;
import com.dtjd.playcoinmonkey.R;
import com.dtjd.playcoinmonkey.activities.main.MainActivity;
import com.dtjd.playcoinmonkey.bean.HttpParaBean;
import com.dtjd.playcoinmonkey.databinding.ActivityLoginBinding;
import com.dtjd.playcoinmonkey.utils.Network;
import com.dtjd.playcoinmonkey.utils.Tools;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity {
    private ActivityResultLauncher<Intent> launcher;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActionBar actionbar = getSupportActionBar();
        if (actionbar!=null){
            actionbar.setDisplayHomeAsUpEnabled(true);
            actionbar.setHomeButtonEnabled(true);
        }
        ActivityLoginBinding binding=ActivityLoginBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setTitle(R.string.login);
        binding.loginSign.setOnClickListener(view -> launcher.launch(new Intent(LoginActivity.this,SignActivity.class)));
        binding.loginPrivacy.setOnClickListener(view -> {
            Intent intent=new Intent(LoginActivity.this,PolicyActivity.class);
            intent.putExtra("type","Privacy");
            startActivity(intent);
        });
        binding.loginServiceItem.setOnClickListener(view -> {
            Intent intent=new Intent(LoginActivity.this,PolicyActivity.class);
            intent.putExtra("type","Service");
            startActivity(intent);
        });
        binding.loginForget.setOnClickListener(view -> launcher.launch(new Intent(LoginActivity.this, FindPasswordActivity.class)));
        binding.loginLogin.setOnClickListener(view -> {
            String email = binding.loginEmail.getText().toString();
            String password = binding.loginPassword.getText().toString();
            if (!binding.loginCb.isChecked()){
                Tools.toast( getResources().getString(R.string.toastclause));
                return;
            }
            if (!email.equals("")&&!password.equals("")){
                ArrayList<HttpParaBean>list=new ArrayList<>();
                list.add(new HttpParaBean("phone",email));
                list.add(new HttpParaBean("password",password));
                Network.post(list, "wbh/wbhLogin", new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        e.printStackTrace();
                    }
                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) {
                        runOnUiThread(()->{
                            try {
                                JSONObject jo = new JSONObject(Objects.requireNonNull(response.body()).string());
                                if (jo.getInt("code")==1){
                                    JSONObject jo1 = jo.getJSONArray("datalist").getJSONObject(0);
                                    @SuppressLint("CommitPrefEdits") SharedPreferences.Editor edit = MyApplication.sp.edit();
                                    edit.putString("token",jo1.getString("token"));
                                    edit.putString("sign",jo1.getString("sign"));
                                    edit.apply();
                                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                                    finish();
                                    MyApplication.wb_money = jo1.getDouble("wb_money");
                                }else {
                                    Tools.toast(jo.getString("datalist"));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        });
                    }
                });
            }else {
                Tools.toast( getResources().getString(R.string.enterComplete));
            }
        });
        launcher=registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode()==3){
                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                finish();
            }
            if (result.getResultCode()==7){
                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                finish();
            }
        });
    }
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (android.R.id.home==item.getItemId()){
            startActivity(new Intent(LoginActivity.this,MainActivity.class));
            finish();
        }
        return super.onOptionsItemSelected(item);
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
      if (keyCode==KeyEvent.KEYCODE_BACK){
          startActivity(new Intent(LoginActivity.this,MainActivity.class));
          finish();
      }
      return super.onKeyDown(keyCode, event);
    }
}